package com.levi.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author shentong
 * @date 2021/10/26 21:07
 * @Description TODO
 */
@Api(tags = "security-测试接口")
@RestController
//@RequestMapping("/security")
public class SecurityController {

    @ApiOperation("r1")
    @GetMapping("/r/r1")
    @PreAuthorize("hasAuthority('p1')")
    public String r1() {
        return getLoginUserName() + " 访问r1页面";
    }

    @ApiOperation("r2")
    @GetMapping("/r/r2")
    @PreAuthorize("hasAuthority('p2')")
    public String r2() {
        return getLoginUserName() + " 访问r2页面";
    }

    @ApiOperation("登录成功跳转路径")
    @PostMapping ("/loginSucess")
    public String loginSucess() {
        return getLoginUserName() + " 登陆成功";
    }

    /**
     * 获取当前登录用户的用户名
     * 登陆成功之后security会把用户信息存到 SecurityContextHolder.getContext()上下文当中
     * @return
     */
    private String getLoginUserName() {
        //获取用户的认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        String username = null;
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        }else {
            username = "游客";
        }
        return username;
    }

}
